//
//  LFFreshOrderTableViewController.m
//  newload
//
//  Created by xue-iOS-work on 16/9/25.
//  Copyright © 2016年 xue. All rights reserved.
#import "UINavigationBar+Awesome.h"
#import "LFFreshOrderTableController.h"//详情tableView
#import "LFFreshOrderTableViewController.h"
#import "ZWNetWorkTools.h"
#import "YYModel.h"
#import "LFOrderTableViewController.h"
// 订单第一层模型
#import "LFFreshOrderActinfoModel.h"
// 订单第二层模型
#import "LFFreshOrderActRowModel.h"
// 订单分类详情模型
#import "LFFreshOrdercategoryDetailModel.h"
// 订单商品详情模型
#import "LFFreshOrdergoodsModel.h"
// 订单更多的模型
#import "LFFreshOrdermoreActivityModel.h"
// 订单activModel模型
#import "LFFreshOrderActivDetailModel.h"
// 分类视图
#import "LFFreshOrderCategoryButton.h"
#import "LFFreshOrderTableViewCell.h"
//cell
#import "UITableViewSecondCell.h"
#import "FeWifiManHub.h"
#import "NewPagedFlowView.h"
#import "PGIndexBannerSubiew.h"
#import "LFHomeSearchViewController.h"
#define NAVBAR_CHANGE_POINT 50
// 注册cell
static NSString *cell_id = @"cell_id";
static NSString *ce_id = @"ce_id";
#define Width [UIScreen mainScreen].bounds.size.width

@interface LFFreshOrderTableViewController ()<UITableViewDelegate,UITableViewDataSource,NewPagedFlowViewDelegate, NewPagedFlowViewDataSource>
@property(nonatomic,strong)NSArray *lunBoArrays;
@property(nonatomic,strong)NSArray *nameArrays;
@property(nonatomic,strong)NSArray *imageNameArrays;
@property(nonatomic,strong)NSArray *backGroudArrays;
//
@property(nonatomic,strong)NSArray *imageArray;
// 第二排商品的数据
@property(nonatomic,strong)NSArray *secondGoodsArray;
// 第三排商品的数据
@property(nonatomic,strong)NSArray *threeGoodsArray;
@property(nonatomic,strong)LFFreshOrderTableController *vc ;
@property(nonatomic,strong)LFFreshOrderTableController *vc1 ;
@property (strong, nonatomic) FeWifiManHub *wifiManHubLoader;
@property (strong, nonatomic) FeWifiManHub *wifiManHubPercent;
@property(strong, nonatomic) UIImageView * bigimage;
@property(nonatomic,strong)UIView *tempView;
// 头部视图
@property(nonatomic,weak)UIView *headerView;

@end

@implementation LFFreshOrderTableViewController
-(LFFreshOrderTableController *)vc
{
    if (_vc==nil) {
        _vc = [[LFFreshOrderTableController alloc]init];
    }
    return _vc;
}
-(LFFreshOrderTableController *)vc1
{
    if (_vc1==nil) {
        _vc1 = [[LFFreshOrderTableController alloc]init];
    }
    return _vc1;
}
    
- (void)viewDidLoad {
    [super viewDidLoad];
    // 初始化UI
    _bigimage = [[UIImageView alloc]initWithFrame:self.view.frame];
    _bigimage.backgroundColor = [UIColor  grayColor];
    _bigimage.alpha = 0.7;
    
    _tempView = [[UIView alloc]initWithFrame:self.view.bounds];
    _tempView.backgroundColor = [UIColor  grayColor];
    _tempView.alpha = 1;
    [self.view addSubview:_tempView];
    [self.navigationController.view addSubview:_bigimage];
    _wifiManHubLoader = [[FeWifiManHub alloc] initWithView:self.view withMode:FeWifiManHubModeOnlyLoader];
    [self.navigationController.view addSubview:_wifiManHubLoader];
    [_wifiManHubLoader show];
    // 加载网络数据
    [self loadInfoDatas];
    NSLog(@"%@",self.navigationController.view);
    //初始化naview1
    UIBarButtonItem *searchBtnItem = [UIBarButtonItem barButtonWithTitle:@"" image:@"icon_search" style:UIBarButtonItemStylePlain target:self action:@selector(clickSearchButton:)];
    self.navigationItem.rightBarButtonItem = searchBtnItem;
    self.navigationController.navigationBar.tintColor = HMColor(255, 226, 139);
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:HMColor(255, 226, 139)] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.alpha = 0.4;
    
}
#pragma mark - 右边搜索按钮
-(void)clickSearchButton:(UIBarButtonItem*)button{
    LFHomeSearchViewController *searchVC = [[LFHomeSearchViewController alloc] init];
    NSMutableArray *ArrayMAll = [NSMutableArray arrayWithArray:self.threeGoodsArray];
    [ArrayMAll addObject:self.secondGoodsArray];
    searchVC.allDataArray = ArrayMAll;
    [UIView animateWithDuration:1 animations:^{
        self.view.alpha = 0;
        self.navigationController.navigationBar.alpha = 0;
    } completion:^(BOOL finished) {
        [self.navigationController pushViewController:searchVC animated:NO];
        self.view.alpha = 1;
        self.navigationController.navigationBar.alpha = 1;
        searchVC.navigationController.navigationBar.alpha = 1;
    }];
    
}
#pragma mark - 添加轮播器的方法
- (void)setCycleView
{
    NewPagedFlowView *pageFlowView = [[NewPagedFlowView alloc] initWithFrame:CGRectMake(0, 0, Width, (Width - 84) * 9 / 16 + 24)];
    pageFlowView.backgroundColor = [UIColor whiteColor];
    pageFlowView.delegate = self;
    pageFlowView.dataSource = self;
    pageFlowView.minimumPageAlpha = 0.4;
    pageFlowView.minimumPageScale = 0.85;
    pageFlowView.backgroundColor = [UIColor redColor];
    pageFlowView.autoTime = 2;
    //提前告诉有多少页
    pageFlowView.orginPageCount = self.imageArray.count;
    NSLog(@"%zd",self.imageArray.count);
    pageFlowView.isOpenAutoScroll = YES;
    
    //初始化pageControl
    UIPageControl *pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, pageFlowView.frame.size.height - 24 - 8, Width, 8)];
    pageFlowView.pageControl = pageControl;
    [pageFlowView addSubview:pageControl];
    /****************************
     使用导航控制器(UINavigationController)
     如果控制器中不存在UIScrollView或者继承自UIScrollView的UI控件
     请使用UIScrollView作为NewPagedFlowView的容器View,才会显示正常,如下
     *****************************/
    [self.headerView addSubview:pageFlowView];
}
#pragma mark NewPagedFlowView Delegate
- (CGSize)sizeForPageInFlowView:(NewPagedFlowView *)flowView {
    return CGSizeMake(Width - 54, (Width - 54) * 9 / 16);
}

- (void)didSelectCell:(UIView *)subView withSubViewIndex:(NSInteger)subIndex
{
    NSLog(@"点击了第%ld张图",(long)subIndex + 1);
    
}

#pragma mark NewPagedFlowView Datasource
- (NSInteger)numberOfPagesInFlowView:(NewPagedFlowView *)flowView {
    return self.imageArray.count;
}

- (UIView *)flowView:(NewPagedFlowView *)flowView cellForPageAtIndex:(NSInteger)index{
    
    PGIndexBannerSubiew *bannerView = (PGIndexBannerSubiew *)[flowView dequeueReusableCell];
    if (!bannerView) {
        bannerView = [[PGIndexBannerSubiew alloc] initWithFrame:CGRectMake(0, 64, Width - 84, (Width - 84) * 9 / 16)];
        bannerView.layer.cornerRadius = 4;
        bannerView.layer.masksToBounds = YES;
    }
    //在这里下载网络图片
    bannerView.mainImageView.image = self.imageArray[index];
    return bannerView;
}

- (void)didScrollToPage:(NSInteger)pageNumber inFlowView:(NewPagedFlowView *)flowView
{
    //        NSLog(@"ViewController 滚动到了第%ld页",pageNumber);
}
#pragma mark - 加载网络数据
-(void)loadInfoDatas{
    // Do any additional setup after loading the view, typically from a nib.
    [[ZWNetWorkTools sharedTools]reques:HttpMethodGet urlstring:@"http://zhengshoudong.qiniudn.com/beereservation.json" parameters:nil completion:^(id respose, NSError *error) {
        if (error!=nil || respose==nil) {
            NSLog(@"%@错误",error);
        }
        NSLog(@"%@",respose);
        // 获取模型数组
        NSArray *array = respose[@"data"][@"act_info"];
        // 获取到 act_info 数组模型
        NSArray *dataInfos = [NSArray yy_modelArrayWithClass:[LFFreshOrderActinfoModel class] json:array];
        //  创建可变数组
        NSMutableArray *arrOneM = [NSMutableArray array];//装的轮播器的图片名称(4)
        NSMutableArray *arrTwoM = [NSMutableArray array];//装的是图片的名称(3)
        NSMutableArray *arrThreeM = [NSMutableArray array];//装的是名称(3)
        NSMutableArray *arrFourM = [NSMutableArray array]; //装的是背景图片(3)
        // 获取到 act _Row 模型
        for (int i = 0 ; i < dataInfos.count; i++) {
            LFFreshOrderActinfoModel *model = dataInfos[i];
            // 取到中间商品详细数据
            NSArray *arrgoods = model.act_rows;
            if (i ==0) {
                NSArray<LFFreshOrderActRowModel *> *ActRowModels = model.act_rows;
                for (LFFreshOrderActRowModel *actRowModel in ActRowModels) {
                    LFFreshOrdermoreActivityModel *m = actRowModel.activity;
                    NSString *imageName = m.img;
                    [arrOneM addObject:imageName];
                }
            }else if (i == 1)
            {
                NSArray<LFFreshOrderActRowModel *> *ActRowModels = model.act_rows;
                for (LFFreshOrderActRowModel *actRowModel in ActRowModels) {
                    LFFreshOrdermoreActivityModel *m = actRowModel.activity;
                    NSString *imageName = m.img;
                    NSString *name = m.name;
                    [arrTwoM addObject:imageName];
                    [arrThreeM addObject:name];
                }
                
            }else if (i == 2)
            {
                NSArray<LFFreshOrderActRowModel *> *ActRowModels = model.act_rows;
                for (LFFreshOrderActRowModel *actRowModel in ActRowModels) {
                    NSString *banner_imgNames = actRowModel.banner_img;
                    [arrThreeM addObject:banner_imgNames];
                }
                self.secondGoodsArray = arrgoods;
                
            }else if (i == 3)
            {
                self.threeGoodsArray = arrgoods;
            }
        }


        dispatch_async(dispatch_get_main_queue(), ^{
            self.lunBoArrays = arrOneM.copy;
            self.imageNameArrays = arrTwoM.copy;
            self.nameArrays = arrThreeM.copy;
            self.backGroudArrays = arrFourM.copy;
            
            [_wifiManHubLoader dismiss];
            // 初始化UI
            [_bigimage removeFromSuperview];
            [_tempView removeFromSuperview];
            
            [self.tableView reloadData];
            [self setupUI];
        });
    }];
}
#pragma mark-获取图片
- (void)getImages{
    NSMutableArray *tempM = [NSMutableArray array];
    for (NSInteger i = 0; i < self.lunBoArrays.count; i ++) {
        NSURL *url = [NSURL URLWithString:self.lunBoArrays[i]];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        if (image!=nil) {
            [tempM addObject:image];
        }
    }
    _imageArray = tempM.copy;
}
// naviBar
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
    {
        UIColor * color = [UIColor colorWithRed:245/255.0 green:200/255.0 blue:40/255.0 alpha:1];
        CGFloat offsetY = scrollView.contentOffset.y;
        if (offsetY > NAVBAR_CHANGE_POINT) {
            CGFloat alpha = MIN(1, 1 - ((NAVBAR_CHANGE_POINT + 64 - offsetY) / 64));
            [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:alpha]];
        } else {
            [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:0]];
        }
    }
    
- (void)viewWillAppear:(BOOL)animated
    {
        [super viewWillAppear:YES];
        self.tableView.delegate = self;
        [self scrollViewDidScroll:self.tableView];
        [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    }
    
- (void)viewWillDisappear:(BOOL)animated
    {
        [super viewWillDisappear:animated];
        self.tableView.delegate = nil;
        [self.navigationController.navigationBar lt_reset];
    }
#pragma mark - 初始化UI界面
-(void)setupUI{
    [self getImages];
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 400, 0.22*Width + (Width - 84) * 9 / 16 )];
    self.headerView = headView;
    [self setCycleView];
    [self.tableView addSubview:headView];
    // 创建一个分类视图
    UIView *categoryViews = [[UIView alloc]initWithFrame:CGRectMake(0, (Width - 84) * 9 / 16 + 24, 400, 70)];
    // 添加到视图上
    categoryViews.backgroundColor = [UIColor whiteColor];
    [headView addSubview:categoryViews];
    // 布局
    for (int i = 0;  i < self.imageNameArrays.count; i++) {
        LFFreshOrderCategoryButton *cateButton = [LFFreshOrderCategoryButton freshOrderCategoryButton];
        CGFloat width = 60;
        CGFloat height = 60;
        CGFloat margin = (self.view.bounds.size.width -self.imageNameArrays.count*width)/(self.imageNameArrays.count + 1)*1.0;
        CGFloat x = (width+margin)*i+margin ;
        CGFloat y = 0;
        cateButton.frame = CGRectMake(x, y, width, height);
        [categoryViews addSubview:cateButton];
        // 赋值
        [cateButton.imageview sd_setImageWithURL:[NSURL URLWithString:self.imageNameArrays[i]]];
        cateButton.nameLabel.text = self.nameArrays[i];
        [cateButton addTarget:self action:@selector(clickCategoryButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    //
    self.tableView.tableHeaderView = headView;
    // 设置数据源
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    // 自动计算行高
    self.tableView.estimatedRowHeight = 400;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    // 取消分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.automaticallyAdjustsScrollViewInsets = NO;
    //添加通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(clickAddButton:) name:@"papapa" object:nil];
    
}
#pragma mark - 实现通知的方法
-(void)clickAddButton:(NSNotification *)sender{
        //显示的总的个数
        int counts = [self.vc1.xianshiCountLabel.text intValue];
        counts++;
        //已选个数
        int count =  [self.vc1.countLabel.text intValue];
//        int count = self.vc1.model.alreadyBuyCount;
        count++;
        self.vc1.model.alreadyBuyCount = count;
        self.vc1.model.allCount = counts;
        self.vc1.countLabel.text = [NSString stringWithFormat:@"%d",self.vc1.model.alreadyBuyCount];
        self.vc1.xianshiCountLabel.text = [NSString stringWithFormat:@"%d",self.vc1.model.allCount];
    // 获取模型
    LFFreshOrdergoodsModel *model =self.vc.model;
    NSLog(@"%@",model);
    UIImageView *imageView = sender.userInfo[@"imageView"];
    
    CGFloat sizeH = self.tabBarController.tabBar.frame.origin.y + 23;
    CGFloat sizeW = self.tabBarController.tabBar.frame.size.width / 5 * 3.5 ;
    CGPoint end = CGPointMake(sizeW, sizeH);
    [self addProductsAnimation:imageView dropToPoint:end isNeedNotification:YES];
    
}
-(void)clickCategoryButton:(LFFreshOrderCategoryButton *)sender{
    NSLog(@"%@",sender.nameLabel.text);
    
}
//#pragma mark - 数据源
//// 多少组
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
// 每组有多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3+9;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 注册
    if(indexPath.row==1||indexPath.row==2||indexPath.row==0)
    {
        // 获取模型
        LFFreshOrderActRowModel * model = self.secondGoodsArray[indexPath.row];
        [self.tableView registerNib:[UINib nibWithNibName:@"LFFreshOrderTableViewCell" bundle:nil] forCellReuseIdentifier:cell_id];
        
        LFFreshOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_id forIndexPath:indexPath];
        
        if (indexPath.row == 0) {
            [cell.imageview sd_setImageWithURL:[NSURL URLWithString:@"http://img01.bqstatic.com//upload/activity/2016070117351813.png@90Q.png"]];
        }else if (indexPath.row == 1)
        {
            [cell.imageview sd_setImageWithURL:[NSURL URLWithString:@"http://img01.bqstatic.com//upload/activity/2016070117373193.png@90Q.png"]];
            
        }else  if (indexPath.row == 2) {
            [cell.imageview sd_setImageWithURL:[NSURL URLWithString:@"http://img01.bqstatic.com//upload/activity/2016092115182391.jpg@90Q.jpg"]];
        }
        void(^myblock)(LFFreshOrdergoodsModel *model) = ^(LFFreshOrdergoodsModel *model){
            
            LFFreshOrderTableController *vc1 = [[LFFreshOrderTableController alloc]init];
            self.vc1 = vc1;
            self.vc1.model = model;
            self.vc1.secondGoodsArray = self.secondGoodsArray;
            self.vc1.threeGoodsArray = self.threeGoodsArray;
            [self.navigationController pushViewController:self.vc1 animated:YES];
            
        };
        cell.myBlock = myblock;
        cell.models = model;
        return cell;
    }
    [self.tableView registerNib:[UINib nibWithNibName:@"UITableViewSecondCell" bundle:nil] forCellReuseIdentifier:ce_id];
    UITableViewSecondCell *cell = [tableView dequeueReusableCellWithIdentifier:ce_id forIndexPath:indexPath];
    // 获取模型
    LFFreshOrderActRowModel * models = self.threeGoodsArray[indexPath.row-3];
    [cell.imageV sd_setImageWithURL:[NSURL URLWithString:models.banner_img]];
    cell.models = models;
    void(^myblock)(LFFreshOrdergoodsModel *model) = ^(LFFreshOrdergoodsModel *model){
        LFFreshOrderTableController *vc = [[LFFreshOrderTableController alloc]init];
        self.vc = vc;
        self.vc.model = model;
        self.vc.threeGoodsArray = self.threeGoodsArray;
        self.vc.secondGoodsArray = self.secondGoodsArray;
        [self.navigationController pushViewController:self.vc animated:YES];
    };
    cell.myBlock = myblock;
    return cell;
    
}

@end
